package info.ensa.googlemapsandroidv2;
import java.util.ArrayList;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class Mapproche extends FragmentActivity implements ConnectionCallbacks,
		OnConnectionFailedListener, LocationListener,
		OnMyLocationButtonClickListener, LocationSource {
	private GoogleMap gMap;
	private LocationClient mLocationClient;
	private static LatLng MELBOURNE = null;
	String longitude;
	double longi;
	String latitude;
	double lati;
	String max;
	int maximum;					
	LocationManager locationManager;
	double distance;
	double distancemin;
	double longitudemin;
	double latitudemin;
	double malongi;
	double malati;

	private static final LocationRequest REQUEST = LocationRequest.create()
			.setInterval(5000) // 5 seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_);

		max = getIntent().getStringExtra("Max");
//		Toast.makeText(getApplicationContext(), "Max= " + max,
//				Toast.LENGTH_LONG).show();
		maximum = Integer.parseInt(max);
		Log.i("Max: ", max);

//		malongi = mLocationClient.getLastLocation().getLongitude();
//		malati = mLocationClient.getLastLocation().getLatitude();
		
		Location here = new Location("Current");
		Location dest = new Location("Destination");

		ArrayList<Double> listelongitude = new ArrayList<Double>();
		ArrayList<Double> listelatitude = new ArrayList<Double>();
		ArrayList<Double> listedistance = new ArrayList<Double>();

		for (int j = 0; j < maximum; j++) {
			longitude = getIntent().getStringExtra("Longitude" + j);
			longi = Double.parseDouble(longitude);
			Log.i("Ma longitude" + j, "" + longi);
//			Toast.makeText(getApplicationContext(),
//					"Longitude" + j + "= " + longitude, Toast.LENGTH_LONG)
//					.show();
			listelongitude.add(longi);

			latitude = getIntent().getStringExtra("Latitude" + j);
			lati = Double.parseDouble(latitude);
			Log.i("Ma latitude" + j, "" + lati);
//			Toast.makeText(getApplicationContext(),
//					"Latitude" + j + "= " + lati, Toast.LENGTH_LONG).show();
			listelatitude.add(lati);

			here.setLatitude(malati);
			here.setLongitude(malongi);
			dest.setLatitude(lati);
			dest.setLongitude(longi);
			distance = here.distanceTo(dest);
			
//			int R = 6371; // km
//			double x = (longi - malongi) * Math.cos((lati + malati) / 2);
//			double y = (lati - malati);
//			double distance = Math.sqrt(x * x + y * y) * R;
			Log.i("Ma distance", "" + distance);
			listedistance.add(distance);
		}
		distancemin = listedistance.get(maximum - 1);
		longitudemin = listelongitude.get(maximum - 1);
		latitudemin = listelatitude.get(maximum - 1);

		for (int i = 0; i < listedistance.size(); i++) {
			if (listedistance.get(i) < distancemin) {
				distancemin = listedistance.get(i);
				longitudemin = listelongitude.get(i);
				latitudemin = listelatitude.get(i);
			}
		}

		Log.i("Distance Min", "" + distancemin);
		Log.i("Longitude Min", "" + longitudemin);
		Log.i("Latitude Min", "" + latitudemin);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.map_, menu);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();
		setUpLocationClientIfNeeded();
		mLocationClient.connect();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLocationClient != null) {
			mLocationClient.disconnect();
		}
	}

	private void setUpMapIfNeeded() {
		if (gMap == null) {
			gMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();

			if (gMap != null) {
				gMap.setMyLocationEnabled(true);
				gMap.setOnMyLocationButtonClickListener(this);
			}

		}
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
					this); // OnConnectionFailedListener
		}

	}

	/**
	 * Button to get current Location. This demonstrates how to get the current
	 * Location as required without needing to register a LocationListener.
	 */
	public void showMyLocation(View view) {
	}

	@Override
	public void activate(OnLocationChangedListener arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMyLocationButtonClick() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnected(Bundle arg0) {

		mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener

		MELBOURNE = new LatLng(mLocationClient.getLastLocation().getLatitude(),
				mLocationClient.getLastLocation().getLongitude());
		gMap.addMarker(new MarkerOptions()
				.position(MELBOURNE)
				.title("Melbourne")
				.snippet("Population: 4,137,400")
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.ic_launcher)));
		gMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
		
		malati= mLocationClient.getLastLocation()
				.getLatitude();
		malongi=mLocationClient.getLastLocation()
				.getLongitude();
		
		new ItineraireTask(this, gMap, malati, malongi, latitudemin, longitudemin).execute();

	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub

	}

}
